package dnl.toolbox.files;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import dnl.jexem.cmd.Command;
import dnl.jexem.cmd.CommandExecution;
import dnl.jexem.cmd.CommandExecutionFactory;

/**
 * An <code>Archiver</code> that is based on excecution of the 'zip' command.
 * 
 * @author Daniel Orr
 * 
 */
public class ZipCommandArchiver implements Archiver {

	private boolean verbose = false;

	public boolean isVerbose() {
		return verbose;
	}

	public void setVerbose(boolean verbose) {
		this.verbose = verbose;
	}

	@Override
	public void createZip(File sourceDir, File target, boolean deleteOrigin) throws IOException {
		Command zipCommand = new Command("bash", "-c", "zip "+target.getAbsolutePath() + " *");
		CommandExecution commandExecution = CommandExecutionFactory
				.createLocalCommandExecution(zipCommand);
		commandExecution.setWorkDir(sourceDir.getAbsolutePath());
		// a 1 second timeout
		commandExecution.executeCommand(0);

		exec(sourceDir, deleteOrigin, commandExecution);
	}


	@Override
	public void unzip(File zipFile, File target, boolean deleteOrigin) throws IOException {
		if(!target.exists()){
			FileUtils.forceMkdir(target);
		}
		CommandExecution commandExecution = CommandExecutionFactory
				.createLocalCommandExecution("unzip", zipFile.getAbsolutePath(), "-d", target
						.getAbsolutePath());
		// a 1 second timeout
		commandExecution.executeCommand(0);

		exec(zipFile, deleteOrigin, commandExecution);
	}


	private void exec(File sourceDir, boolean deleteOrigin, CommandExecution commandExecution) {
		if (verbose) {
			System.out.println("Output: " + commandExecution.getOutput());
		}

		// if we had errors
		if (commandExecution.getExitStatus() != 0) {
			System.err.println("Error: " + commandExecution.getErrorOutput());
			String[] exceptionMessages = commandExecution.getExceptionMessages();
			for (String e : exceptionMessages) {
				System.err.println("Error: " + e);
			}
			return;
		}

		if (deleteOrigin) {
			try {
				FileUtils.forceDelete(sourceDir);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
